#include "StdAfx.h"
#include "MultiLineEditWnd.h"
#include "MultiLineEditUI.h"

CMultiLineEditWnd::CMultiLineEditWnd(void):m_pOwner(NULL)
{
}

CMultiLineEditWnd::~CMultiLineEditWnd(void)
{
}

void CMultiLineEditWnd::Init(CMultiLineEditUI* pOwner)
{
	RECT rcPos = pOwner->GetPos();
	::InflateRect(&rcPos, -1, -3);
	Create(pOwner->m_pManager->GetPaintWindow(), NULL, 
		WS_CHILD | WS_CLIPCHILDREN | WS_CLIPSIBLINGS | WS_VSCROLL | ES_MULTILINE | ES_AUTOVSCROLL, 0, 
		rcPos,(HMENU)NULL);
	SetWindowFont(m_hWnd, pOwner->m_pManager->GetThemeFont(UIFONT_NORMAL), TRUE);
	Edit_SetText(m_hWnd, pOwner->m_sText);
	Edit_SetModify(m_hWnd, FALSE);
	SendMessage(EM_SETMARGINS, EC_LEFTMARGIN | EC_RIGHTMARGIN, MAKELPARAM(2, 2));
	Edit_SetReadOnly(m_hWnd, pOwner->IsReadOnly() == true);
	Edit_Enable(m_hWnd, pOwner->IsEnabled() == true);
	if( pOwner->IsVisible() ) ::ShowWindow(m_hWnd, SW_SHOWNOACTIVATE);
	m_pOwner = pOwner;
}

LPCTSTR CMultiLineEditWnd::GetWindowClassName() const
{
	return _T("MultiLineEditWnd");
}

LPCTSTR CMultiLineEditWnd::GetSuperClassName() const
{
	return WC_EDIT;
}

void CMultiLineEditWnd::OnFinalMessage(HWND /*hWnd*/)
{
	m_pOwner->m_pWindow = NULL;
	delete this;
}

LRESULT CMultiLineEditWnd::HandleMessage(UINT uMsg, WPARAM wParam, LPARAM lParam)
{
	LRESULT lRes = 0;
	BOOL bHandled = TRUE;
	if( uMsg == OCM_COMMAND && GET_WM_COMMAND_CMD(wParam, lParam) == EN_CHANGE ) lRes = OnEditChanged(uMsg, wParam, lParam, bHandled);
	else bHandled = FALSE;
	if( !bHandled ) return CWindowWnd::HandleMessage(uMsg, wParam, lParam);
	return lRes;
}

LRESULT CMultiLineEditWnd::OnEditChanged(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)
{
	if( m_pOwner == NULL ) return 0;
	// Copy text back
	int cchLen = ::GetWindowTextLength(m_hWnd) + 1;
	LPTSTR pstr = static_cast<LPTSTR>(_alloca(cchLen * sizeof(TCHAR)));
	ASSERT(pstr);
	::GetWindowText(m_hWnd, pstr, cchLen);
	m_pOwner->m_sText = pstr;
	m_pOwner->GetManager()->SendNotify(m_pOwner, _T("changed"));
	return 0;
}
